// FileAnalysisService.java
package com.webguard.outlierdetection.service;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Service
public class FileAnalysisService {
    private static final Logger logger = LoggerFactory.getLogger(FileAnalysisService.class);
    private static final int STORAGE_CAPACITY = 100_000;
    private static final int BATCH_SUBMIT_SIZE = 50;

    private final LLMService llmService;
    private final BlockingQueue<String> dataBuffer = new LinkedBlockingQueue<>(STORAGE_CAPACITY);

    public FileAnalysisService(LLMService llmService) {
        this.llmService = llmService;
        startDataCoordinator();
    }

    @Async
    public void processUploadedFile(MultipartFile file, String format) throws IOException {
        final String filename = file.getOriginalFilename();
        final String fileType = detectFileType(filename, format);

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            switch (fileType.toLowerCase()) {
                case "csv" -> processCSV(reader);
                case "jsonl" -> processJSONL(reader);
                case "txt" -> processTXT(reader);
                default -> throw new IllegalArgumentException("不支持的文件格式: " + fileType);
            }
            logger.info("文件解析完成: {}", filename);
        } catch (CsvValidationException e) {
            throw new IllegalArgumentException("CSV格式验证失败");
        }
    }

    private String detectFileType(String filename, String format) {
        if (!"auto".equals(format)) return format;

        if (filename.endsWith(".csv")) return "csv";
        if (filename.endsWith(".jsonl")) return "jsonl";
        if (filename.endsWith(".txt")) return "txt";
        throw new IllegalArgumentException("无法自动识别文件类型");
    }

    private void processCSV(BufferedReader reader) throws IOException, CsvValidationException {
        try (CSVReader csvReader = new CSVReader(reader)) {
            String[] headers = csvReader.readNext(); // 读取表头
            String[] record;
            while ((record = csvReader.readNext()) != null) {
                dataBuffer.put(convertCSVToJSON(headers, record));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private void processJSONL(BufferedReader reader) throws IOException {
        reader.lines()
                .filter(line -> !line.trim().isEmpty())
                .forEach(line -> {
                    try {
                        dataBuffer.put(validateJSON(line));
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
    }

    private void processTXT(BufferedReader reader) throws IOException {
        reader.lines()
                .filter(line -> !line.trim().isEmpty())
                .forEach(line -> {
                    try {
                        dataBuffer.put(parseTxtLine(line));
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
    }

    private String convertCSVToJSON(String[] headers, String[] values) {
        StringBuilder json = new StringBuilder("{");
        for (int i = 0; i < headers.length; i++) {
            json.append(String.format("\"%s\":\"%s\"", headers[i], values[i]));
            if (i < headers.length - 1) json.append(",");
        }
        return json.append("}").toString();
    }

    private String validateJSON(String json) {
        if (!json.startsWith("{") || !json.endsWith("}")) {
            throw new IllegalArgumentException("无效的JSON格式: " + json);
        }
        return json;
    }

    private String parseTxtLine(String line) {
        // 示例解析逻辑：key=value,key2=value2
        String[] pairs = line.split(",");
        StringBuilder json = new StringBuilder("{");
        for (int i = 0; i < pairs.length; i++) {
            String[] kv = pairs[i].split("=");
            if (kv.length != 2) continue;
            json.append(String.format("\"%s\":\"%s\"", kv[0].trim(), kv[1].trim()));
            if (i < pairs.length - 1) json.append(",");
        }
        return json.append("}").toString();
    }

    private void startDataCoordinator() {
        new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    if (llmService.queueRemainingCapacity() > BATCH_SUBMIT_SIZE) {
                        submitBatch(BATCH_SUBMIT_SIZE);
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "DataCoordinator").start();
    }

    private void submitBatch(int batchSize) throws InterruptedException {
        for (int i = 0; i < batchSize; i++) {
            String data = dataBuffer.poll(1, TimeUnit.SECONDS);
            if (data == null) break;
            llmService.submitRawData(data);
        }
    }
}
